﻿CREATE PROCEDURE dbo.s_MovePage
	(
		@LoanID int,
		@ImageTypeID_From int,
		@PageNumber_From int,
		@ImageTypeID_To int,
		@PageNumber_To int
	)
AS

EXEC sh_Debug_Put '@LoanID:$0,@ImageTypeID_From:$1,@PageNumber_From:$2,@ImageTypeID_To:$3,@PageNumber_To:$4',
		@LoanID,		@ImageTypeID_From,		@PageNumber_From,		@ImageTypeID_To,		@PageNumber_To



DECLARE @PageID int,@ImageID_To int

BEGIN TRAN

-- Get ID of destination Image Folder
SELECT @ImageID_To = ID FROM t_Image WHERE LoanID = @LoanID AND ImageTypeID = @ImageTypeID_To
IF @ImageID_To IS NULL BEGIN
	INSERT INTO t_Image(LoanID,ImageTypeID)VALUES(@LoanID,@ImageTypeID_To)
	SET @ImageID_To = IDENT_CURRENT('t_Image')
END
-- Get ID of page being moved
SELECT @PageID = t_Page.ID
FROM  t_Image INNER JOIN t_Page ON t_Image.ID = t_Page.ImageID
WHERE t_Image.ImageTypeID = @ImageTypeID_From AND
			t_Image.LoanID = @LoanID AND
			t_Page.PageNumber = @PageNumber_From

EXEC sh_Debug_Put 's_MovePage<>@ImageID:$0,@PageNumber_To:$1,@PageID:$2',@ImageID_To,@PageNumber_To,@PageID

IF @ImageTypeID_From = @ImageTypeID_To AND @PageNumber_To > @PageNumber_From
	SET @PageNumber_To = @PageNumber_To - 1

-- Move page down to avoid PageNumber collision when moved to new folder
UPDATE t_Page
SET PageNumber_ = 99999
WHERE ID = @PageID
-- Move page and new assign PageNumber
UPDATE t_Page
SET PageNumber_ = @PageNumber_To, ImageID = @ImageID_To
WHERE ID = @PageID

COMMIT TRAN

RETURN @PageNumber_To


